package me.wangshier.pdf;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PDFImageExtractor {
    public static void extractImages(String pdfPath) throws IOException {
        PDDocument document = PDDocument.load(new File(pdfPath));
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) {
            PDPage page = document.getPage(pageIndex);
//            for (PDImageXObject image : page.getResources().getImages()) {
//                // 保存图片
//                File outputFile = new File("image" + pageIndex + ".png");
//                ImageIO.write(image.getImage(), "PNG", outputFile);
//            }
        }
        document.close();
    }

    void extractSingleImage(){
        int pageIndex = 0;
        String picPath = "C:\\Users\\Tung\\Documents\\孙倩雯\\images\\";
        String pdfPath = "C:\\Users\\Tung\\Documents\\孙倩雯\\521 Imventory Quantity list.pdf";
        List<String> images = new ArrayList<>();
        try {
            FileInputStream fis = new FileInputStream(new File(pdfPath));
            PDDocument load = PDDocument.load(fis);
            PDPage page = load.getPage(pageIndex);
            PDResources resources = page.getResources();
            Iterable<COSName> xon = resources.getXObjectNames();
            if(xon!=null){
                Iterator<COSName> iterator = xon.iterator();
                int i = 1;
                while(iterator.hasNext()){
                    COSName key = iterator.next();
                    if(resources.isImageXObject(key)){
                        PDImageXObject image = (PDImageXObject) resources.getXObject(key);
                        BufferedImage bImage = image.getImage();
                        String iUrl = picPath+"pic"+pageIndex+i+"."+image.getSuffix();
                        ImageIO.write(bImage, image.getSuffix(), new File(iUrl));
                        System.out.println("保存图片 "+iUrl);
                        i++;
                    }else {
                        System.out.printf("key = [%s] 不是图片格式", key);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        PDFImageExtractor extractor = new PDFImageExtractor();
        extractor.extractSingleImage();
    }
}
